# -*- coding: utf-8 -*-

'''
@project : FaceRecognition_v7
@FileName: tv1
@Author  :linych 
@Time    :2021/2/18 20:16
@Desc  : 
'''

import ffmpeg
import numpy as np
import cv2
import base64
from VideoAnalysis.Download import video_load




import os
import time

os.environ['http_proxy']='http://10.143.165.150:7001'
os.environ['https_proxy']='http://10.143.165.150:7001'

#
# vpath = r'/home/face/ffmpeg/ffmpeg-4.3.1-amd64-static/ps/20210127130801-20210127130807_ALARM.ps'
# probe = ffmpeg.probe(vpath)
# vinput = ffmpeg.input(vpath)





def decoder(vpath):

    start_time = time.time()

    probe = ffmpeg.probe(vpath)
    vinput = ffmpeg.input(vpath)


    vinput, probe = video_load.dowmload(vpath)


    video_info = next(s for s in probe['streams'] if s['codec_type'] == 'video')
    width = int(video_info['width'])
    height = int(video_info['height'])
    #num_frames = int(video_info['nb_frames'])

    out, err = (
        vinput
        .filter('fps', '1')
        .output('pipe:', format='rawvideo', pix_fmt='rgb24')
        .global_args('-loglevel', 'quiet')
        .run(capture_stdout=True)
    )
    video = (
        np
        .frombuffer(out, np.uint8)
        .reshape([-1, height, width, 3])
    )
    

    res_list = []
    for i in range(len(video)):
        retval, buffer = cv2.imencode('.jpg', video[i])
        pic_str = base64.b64encode(buffer)
        pic_str = pic_str.decode()

        res_list.append(pic_str)
    
    print('decoder use : {}'.format(time.time()-start_time))
    return res_list


def decoder1(vinput,probe):
    start_time = time.time()

    video_info = next(s for s in probe['streams'] if s['codec_type'] == 'video')
    width = int(video_info['width'])
    height = int(video_info['height'])
    # num_frames = int(video_info['nb_frames'])

    out, err = (
        vinput
            .filter('fps', '1')
            .output('pipe:', format='rawvideo', pix_fmt='rgb24')
            .global_args('-loglevel', 'quiet')
            .run(capture_stdout=True)
    )
    video = (
        np
            .frombuffer(out, np.uint8)
            .reshape([-1, height, width, 3])
    )

    res_list = []
    for i in range(len(video)):
        retval, buffer = cv2.imencode('.jpg', video[i])
        pic_str = base64.b64encode(buffer)
        pic_str = pic_str.decode()

        res_list.append(pic_str)

    print('decoder use : {}'.format(time.time() - start_time))
    return res_list





